package com.shopping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShoppingCart {
    private static final int CART_CAPACITY = 10;
    private Map<Product, Integer> cartItems;
    public ShoppingCart() {
        cartItems = new HashMap<>();
    }
    public void addProduct(Product product, int quantity) {
        if (cartItems.containsKey(product)) {
            int currentQuantity = cartItems.get(product);
            int newQuantity = currentQuantity + quantity;
            if (newQuantity > product.getStock()) {
                System.out.println("库存不足，无法添加更多！");
            } else if (getTotalQuantity() + quantity > CART_CAPACITY) {
                System.out.println("购物车已满，无法添加更多商品！");
            } else {
                cartItems.put(product, newQuantity);
                product.setNumberInCart(newQuantity);
            }
        } else {
            if (quantity > product.getStock()) {
                System.out.println("库存不足，无法添加！");
            } else if (getTotalQuantity() + quantity > CART_CAPACITY) {
                System.out.println("购物车已满，无法添加更多商品！");
            } else {
                cartItems.put(product, quantity);
                product.setNumberInCart(quantity);
            }
        }
    }
    public void viewCart() {
        if (cartItems.isEmpty()) {
            System.out.println("购物车中无商品");
        } else {
            System.out.println("购物车中商品：");
            for (Map.Entry<Product, Integer> entry : cartItems.entrySet()) {
                System.out.println(entry.getKey() + " × " + entry.getValue());
            }
        }
    }
    public void removeProduct(Product product) {
        if (cartItems.containsKey(product)) {
            cartItems.remove(product);
            product.setNumberInCart(0);
            System.out.println("已删除该商品！");
        } else {
            System.out.println("购物车中没有此商品！");
        }
    }
    public double checkout() {
        double total = 0;
        if (!cartItems.isEmpty()) {
            for (Map.Entry<Product, Integer> entry : cartItems.entrySet()) {
                total += entry.getKey().getPrice() * entry.getValue();
            }
        }
        cartItems.clear();
        return total;
    }
    private int getTotalQuantity() {
        int total = 0;
        for (Map.Entry<Product, Integer> entry : cartItems.entrySet()) {
            total += entry.getValue();
        }
        return total;
    }
}